package cn.lingyangwl.agile.msg.push.core.channel.client;

import cn.lingyangwl.agile.model.module.config.param.sms.*;
import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.*;
import cn.lingyangwl.agile.msg.push.model.rqrs.channel.*;
import cn.lingyangwl.framework.log.common.*;
import cn.lingyangwl.framework.sms.manager.*;
import cn.lingyangwl.framework.sms.manager.entity.*;
import cn.lingyangwl.framework.sms.properties.*;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

/**
 * 阿里短信客户端
 * @author shenguangyang
 */
@Getter
@Setter
@Slf4j
@EqualsAndHashCode(callSuper = true)
public class SmsAliyunMsgClient extends AbstractSmsMsgClient {
    private AliyunSmsManager aliyunSmsManager;
    private AliyunSmsParam paramConfig;

    @Override
    public ChannelCodeEnum channelCode() {
        return ChannelCodeEnum.SMS_ALIYUN;
    }

    @Override
    public void init() {
        paramConfig = (AliyunSmsParam) msgChannel.getParamConfig();

        AliyunSmsProperties properties = new AliyunSmsProperties();
        properties.setAccessKeyId(paramConfig.getAccessKey());
        properties.setAccessKeySecret(paramConfig.getAccessKeySecret());
        aliyunSmsManager = new AliyunSmsManager(properties);
    }

    public SmsAliyunMsgClient(MsgChannel msgChannel) {
        super(msgChannel);
    }

    @Override
    public SmsChannelResp send(PushTaskContext context) {
        MsgParam msgParam = context.getMsgParam();
        MsgSettings msgSettings = context.getMsgSettings();

        log.debug("send msg to aliyun sms, msg: {}", JSON.toJSONString(msgSettings, JSONWriter.Feature.WriteEnumsUsingName));

        JSONObject data = new JSONObject();
        msgSettings.getTplField().values().forEach(e -> data.put(e.getKey(), e.getValue()));

        AliyunSmsReq smsReq = new AliyunSmsReq();
        smsReq.setSignName(paramConfig.getSignName());
        smsReq.setPhoneNumbers(msgParam.getToUser());
        smsReq.setTemplateId(msgSettings.getTemplateId());
        smsReq.setOutId(MDC.get(LogCons.TRACE_ID));
        smsReq.setTemplateParam(data);
        AliyunSmsReps send = aliyunSmsManager.send(smsReq);
        return SmsChannelResp.builder().success(send.isSuccess()).content(send.getMessage()).build();
    }
}
